package com.coocaa.optimizer.movie.cleaner;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;

import com.coocaa.app.lib.cleaner.mgr.Cleaner;
import com.coocaa.app.lib.cleaner.mgr.CleanerManager;
import com.coocaa.app.lib.cleaner.mgr.DataHolder;
import com.coocaa.app.lib.cleaner.utils.HttpUtils;
import com.coocaa.optimizer.OptimizerApplication;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class CleanerService extends IntentService {
    private static final String ACTION_SCAN_AND_AUTO_CLEAN = "com.coocaa.optimizer.movie.cleaner.service.action.ACTION_SCAN_AND_AUTO_CLEAN";
    private static final String ACTION_CLEAN_END_RECEIVER = "com.coocaa.optimizer.clean.action.end";

    public CleanerService() {
        super("CleanerService");
    }

    public static void startScanAndAutoClean(Context context) {
        try {
            Intent intent = new Intent(context, CleanerService.class);
            intent.setAction(ACTION_SCAN_AND_AUTO_CLEAN);
            context.startService(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_SCAN_AND_AUTO_CLEAN.equals(action)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
//                            int xDay = HttpUtils.getServerXDay();
                            int xDay = 180;  //跟唐思静确认了，系统优化走跟应用圈静默升级，自升级一样的策略，写死卸载180天的app，同时不清除应用数据
                            if (xDay > 0)
                                handleScanAndAutoClean(xDay);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        }
    }

    private void sendCleanEndReceiver(Context mContext){
        try {
            Intent intent = new Intent();
            intent.setAction(ACTION_CLEAN_END_RECEIVER);
            mContext.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleScanAndAutoClean(final int xDay) {
        OptimizerApplication.d("~~~~~~~start ScanAndAutoClean");
        final Cleaner cleaner = CleanerManager.manager.instance(getApplicationContext());
        cleaner.setCleanerListener(new Cleaner.CleanerListener() {

            Handler handler = null;

            @Override
            public void onScanStart() {
                OptimizerApplication.d(">>>>>>>>>>>>>>>onScanStart");
            }

            @Override
            public synchronized void onScanEnd() {
                OptimizerApplication.d(">>>>>>>>>>>>>>>onScanEnd");
                if (handler == null) {
                    final HandlerThread ht = new HandlerThread("CT");
                    ht.start();
                    handler = new Handler(ht.getLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            OptimizerApplication.d("????clean start!!!!!");
                            long size = cleaner.clearAllPackageCache();
                            size += cleaner.clearAllApkRubbish();
                            size += cleaner.clearAllOtherData();
//                            size += cleaner.clearAllPackageData();  //确认了，不清理应用数据
                            cleaner.unInstallApp(xDay);
                            sendCleanEndReceiver(getApplicationContext());
                            OptimizerApplication.d("????clean end!!!!!  " + size);
                            android.os.Process.killProcess(android.os.Process.myPid());
                        }
                    });
                }
            }

            @Override
            public void onCleanAllStart() {

            }

            @Override
            public void onCleanAllEnd(long size) {

            }

            @Override
            public void onApkRubbishUpdate(DataHolder.ApkRubbish apkRubbish, String apkFile) {
//                OptimizerApplication.d("{{onApkRubbishUpdate total:" + apkRubbish.size);
            }

            @Override
            public void onPackageCacheUpdate(DataHolder.PackageCache packageCache, String packageName) {
//                OptimizerApplication.d("{{onPackageCacheUpdate total:" + packageCache.size + "@" + packageName);
            }

            @Override
            public void onPackageDataUpdate(DataHolder.PackageData packageData, String packageName) {
//                OptimizerApplication.d("{{onPackageDataUpdate total:" + packageData.size + "@" + packageName);
            }

            @Override
            public void onOtherDataUpdate(DataHolder.OtherData otherData, String file) {
//                OptimizerApplication.d("{{onOtherDataUpdate total:" + otherData.size);
            }
        });
        cleaner.startScan();
        OptimizerApplication.d("~~~~~~~end ScanAndAutoClean");
    }
}
